package cc.rengu.redp.bizimpl.csmc.service.impl;

import cc.rengu.redp.bizimpl.csmc.common.CsmcConstant;
import cc.rengu.redp.bizimpl.csmc.domain.CSettleRule;
import cc.rengu.redp.bizimpl.csmc.dao.CSettleRuleMapper;
import cc.rengu.redp.bizimpl.csmc.service.ICSettleRuleService;
import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.BizTmp;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpPrivilegeCheck;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author lizk
 */
@Service
@DS("csmc")
public class CSettleRuleServiceImpl extends ServiceImpl<CSettleRuleMapper, CSettleRule> implements ICSettleRuleService {

    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IUpmpPrivilegeCheckService authPrivilegeCheckService;
    @Autowired
    private IBizTmpService bizTmpService;
    @Autowired
    private IBizHisService bizHisService;
    @Autowired
    private IUpmpSysSeqService sysSeqService;

    private long oprMenuId = 1;
    private String oprMenuName = "清分清算参数管理:清算规则配置";
    private long chkMenuId = 2;
    private String chkMenuName = "清分清算参数管理:清算规则配置";
    private String webNextUrl = "/admin/csmc/settleRule";


    @Override
    public IPage<CSettleRule> findByPage(QueryRequest queryRequest, CSettleRule settleRule) {

        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);

        try {
            String instId = settleRule.getInstId();
            if (Common.isBlank(instId)) {
                instId = user.getInstId();
            }
            LambdaQueryWrapper<CSettleRule> queryWrapper = new LambdaQueryWrapper<>();
            if (!StringUtils.isEmpty(instId)) {
                queryWrapper.eq(CSettleRule::getInstId, instId);
            }
            if (!StringUtils.isEmpty(settleRule.getSettleRuleDesc())) {
                queryWrapper.like(CSettleRule::getSettleRuleDesc, settleRule.getSettleRuleDesc());
            }
            Page<CSettleRule> page = new Page<>();
            SortUtil.handlePageSort(queryRequest, page, true);
            return this.page(page, queryWrapper);
        } catch (Exception e) {
            log.error("获取清算规则信息失败", e);
            return null;
        }
    }

    @Override
    public void createSettleRule(CSettleRule settleRule) throws RedpException {
        saveData(settleRule);
    }

    @Override
    public void updateSettleRule(CSettleRule settleRule) throws RedpException {
        saveData(settleRule);
    }

    @Override
    public Map<String, Object> tagsData(String q, QueryRequest request) {

        if (null == q) {
            return null;
        }

        try {
            LambdaQueryWrapper<CSettleRule> queryWrapper = new LambdaQueryWrapper<>();

            if (org.apache.commons.lang3.StringUtils.isNotEmpty(q)) {
                queryWrapper.and(qw -> qw.likeRight(CSettleRule::getSettleRuleId, q)
                        .or().likeRight(CSettleRule::getSettleRuleDesc, q));
            }

            Page<CSettleRule> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            Page<CSettleRule> page1 = this.page(page, queryWrapper);
            List<CSettleRule> listx = page1.getRecords();
            Map<String, Object> maps = new HashMap<String, Object>();
            Map<String, String> map = new HashMap<String, String>();
            List<Object> list = new ArrayList<Object>();
            if (listx != null) {
                for (int i = 0; i < listx.size(); i++) {
                    CSettleRule org = listx.get(i);
                    map = new HashMap<String, String>();
                    map.put("id", org.getSettleRuleId());
                    map.put("name", org.getSettleRuleDesc());

                    list.add(map);
                }
                maps.put("results", list);
                maps.put("total", page.getTotal());
                int pageIndex = Common.isBlank(request.getPageNum()) ? 1 : request.getPageNum();
                if (pageIndex == page1.getTotal()) {
                    maps.put("more", false);
                } else {
                    maps.put("more", true);
                }
            }
            return maps;

        } catch (Exception e) {
            log.error("获取信息失败", e);
            return null;
        }
    }

    /**
     * 系统生成清算规则标识（格式：S + 7位序号）
     *
     * @return
     */
    private String generateCode() {
        // 固定入参
        String common = "COMM_PARAM_CODE";
        // 清算标识前缀：IN
        String prefix = CsmcConstant.SettleRuleId_PREFIX;
//        // 渠道ID：固定值20
//        String channelId = CommonUtils.getChannelId(dataDictService);
        // 生成序列号
        String serialNumber = sysSeqService.updateParamValue(common, prefix, "");
        // 编码：AE + 6位顺序编号
        String result = prefix + String.format("%07d", Integer.parseInt(serialNumber));
        return result;
    }

    private void saveData(CSettleRule entity)  throws RedpException {

        String optFlag = entity.getOptFlag();

        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);

//        entity.setInstId(user.getInstId());

        if (PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)) {
            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "settleRule:add");
            entity.setId(null);
            entity.setOprId(user.getId());
            entity.setCreateTime(lastUpddt);
            entity.setSettleRuleId(generateCode());
            //
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
                entity.setOprStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                this.save(entity);
                bizTmpService.saveBizTmp(entity, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        entity.getOprStatus(), entity.getAuditStatus(), entity.getId(), webNextUrl, null, null, null);

            } else {

                entity.setOprStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                this.save(entity);
                bizHisService.saveBizHisNew(entity, entity, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        entity.getId(), null, null, null);

            }
        } else if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(optFlag)) {


            String id = entity.getId();
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }


            UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "settleRule:edit");


            CSettleRule dbsettlerule = baseMapper.selectById(id);
            CSettleRule settlerule = new CSettleRule();
            CSettleRule settleruleTmp = new CSettleRule();
            BeanUtils.copyProperties(dbsettlerule, settlerule);
            BeanUtils.copyProperties(dbsettlerule, settleruleTmp);

            entity.setAuditOprId(user.getId());
            entity.setUpdateTime(lastUpddt);
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                settlerule.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                baseMapper.updateById(settlerule);
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
                BeanUtils.copyProperties(entity, settleruleTmp);

                //检查临时表是否有数据，如果没用则新增
                bizTmpService.saveBizTmp(settleruleTmp, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        settleruleTmp.getOprStatus(), settleruleTmp.getAuditStatus(), settleruleTmp.getId(), webNextUrl, null, null, null);

            } else {
                entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                BeanUtils.copyProperties(entity, settlerule);
                baseMapper.updateById(settlerule);

                bizHisService.saveBizHisNew(settlerule, dbsettlerule, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        settlerule.getId(), null, null, null);

            }
        } else if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(optFlag)
                || PageOptFlagEnum.OPT_FLAG_USE.getType().equals(optFlag)
                || PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(optFlag)) {

            String id = entity.getId();
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }
            CSettleRule settleruledb = baseMapper.selectById(id);
            CSettleRule settlerule = new CSettleRule();
            BeanUtils.copyProperties(settleruledb, settlerule);
            if (Common.isBlank(settlerule)) {
                log.error("根据id没有找到指定数据！");
                throw new RedpException("根据id没有找到指定数据！");
            }
            UpmpPrivilegeCheck privilegeCheck = new UpmpPrivilegeCheck();
            String bizOpr = "";
            if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(optFlag)) {
                bizOpr = BizOprEnum.OPR_STOP.getType();
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "settleRule:stop");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    settlerule.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType());
                } else {
                    settlerule.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                    settlerule.setOprStatus(BizDataStatusEnum.STATUS_STOPED.getType());
                }
                settlerule.setStopReason(entity.getStopReason());
            } else if (PageOptFlagEnum.OPT_FLAG_USE.getType().equals(optFlag)) {

                bizOpr = BizOprEnum.OPR_USE.getType();
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "settleRule:use");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    settlerule.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType());
                } else {
                    settlerule.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                    settlerule.setOprStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                }
            } else if (PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(optFlag)) {


                bizOpr = BizOprEnum.OPR_CANCEL.getType();
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "settleRule:cancel");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    settlerule.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType());
                } else {
                    settlerule.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                    settlerule.setOprStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
                }
                settlerule.setCancelReason(entity.getCancelReason());
            }
            settlerule.setAuditOprId(user.getId());
            settlerule.setUpdateTime(lastUpddt);
            baseMapper.updateById(settlerule);

            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                //检查临时表是否有数据，如果没用则新增
                bizTmpService.saveBizTmp(settlerule, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        settlerule.getOprStatus(), settlerule.getAuditStatus(), settlerule.getId(), webNextUrl, null, null, null);

            } else {
                //历史表新增
                bizHisService.saveBizHisNew(settlerule, settleruledb, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(oprMenuId), oprMenuName,
                        settlerule.getId(), null, null, null);

            }
        } else if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {

            String id = entity.getId();
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常!");
            }

            //获取临时表数据并转换成实体对象
            BizTmp tmp = bizTmpService.getBizTmpDetail(id);
            if (Common.isBlank(tmp)) {
                log.error("根据id没有找到指定临时表数据！");
                throw new RedpException("根据id没有找到指定临时表数据！");
            }
            String bizdata = "";
            if (null != tmp.getBizData1()) {
                bizdata += tmp.getBizData1();
            }
            if (null != tmp.getBizData2()) {
                bizdata += tmp.getBizData2();
            }
            if (null != tmp.getBizData3()) {
                bizdata += tmp.getBizData3();
            }
            CSettleRule settleruleNew = JSON.parseObject(bizdata, CSettleRule.class);
            CSettleRule settlerule = baseMapper.selectById(id);
            CSettleRule settleruleld = new CSettleRule();
            BeanUtils.copyProperties(settlerule, settleruleld);

            if (Common.isBlank(settlerule) && !BizOprEnum.OPR_ADD.equals(tmp.getBizOpr())) {
                log.error("根据id没有找到指定数据！");
                throw new RedpException("根据id没有找到指定数据！");
            }

            String opt = entity.getOpt();
            if (Common.isBlank(opt)) {
                log.error("请求参数(opt)异常!");
                throw new RedpException("请求参数(opt)异常!");
            }

            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                // 审批通过将临时表数据更新到正式表
                BeanUtils.copyProperties(settleruleNew, settlerule);
            } else {
                String approvalRefuseReason = entity.getAuditRefuseReason();
                settlerule.setAuditRefuseReason(approvalRefuseReason);
            }

            String bizOpr = "";
            BeanUtils.copyProperties(settleruleNew, settlerule);
            if (BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType().equals(settlerule.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    settlerule.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                    settlerule.setOprStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                } else {
                    settlerule.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_ADD.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType().equals(settlerule.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    settlerule.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                    settlerule.setOprStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
                } else {
                    settlerule.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_CANCEL.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType().equals(settlerule.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    settlerule.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                    settlerule.setOprStatus(BizDataStatusEnum.STATUS_STOPED.getType());
                } else {
                    settlerule.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_STOP.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType().equals(settlerule.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    settlerule.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                    settlerule.setOprStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                } else {
                    settlerule.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_USE.getType();
            } else if (BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType().equals(settlerule.getAuditStatus())) {
                if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                    settlerule.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                    settlerule.setOprStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                } else {
                    settlerule.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_REJECT.getType());
                }
                bizOpr = BizOprEnum.OPR_UPDATE.getType();
            }
            baseMapper.updateById(settlerule);
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                //审批通过将正式表更新到历史表
                bizHisService.saveBizHisNew(settlerule, settleruleld, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                        String.valueOf(chkMenuId), chkMenuName,
                        settlerule.getId(), null, null, null);

            }
            // 修改临时表的审核状态等字段
            bizTmpService.saveBizTmp(settlerule, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(), lastUpddt,
                    String.valueOf(chkMenuId), chkMenuName,
                    settlerule.getOprStatus(), settlerule.getAuditStatus(), settlerule.getId(), webNextUrl, null, null, null);
        }

    }
}
